package com.waikuai.shop.controller;

import com.waikuai.shop.common.result.Result;
import com.waikuai.shop.entity.Role;
import com.waikuai.shop.service.RoleService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 角色管理控制器
 * @author waikuai
 */
@Slf4j
@RestController
@RequestMapping("/roles")
@RequiredArgsConstructor
public class RoleController {

    private final RoleService roleService;

    /**
     * 获取所有启用的角色列表
     */
    @GetMapping
    @PreAuthorize("hasRole('ROLE_ADMIN')")
    public Result<List<Role>> getAllRoles() {
        log.info("获取所有角色列表");
        
        try {
            List<Role> roles = roleService.getAllEnabledRoles();
            return Result.success("查询成功", roles);
        } catch (Exception e) {
            log.error("获取角色列表失败: {}", e.getMessage(), e);
            return Result.error("查询失败");
        }
    }

    /**
     * 根据用户ID获取角色列表
     */
    @GetMapping("/user/{userId}")
    @PreAuthorize("hasRole('ROLE_ADMIN')")
    public Result<List<Role>> getRolesByUserId(@PathVariable Long userId) {
        log.info("获取用户角色列表: userId={}", userId);
        
        try {
            List<Role> roles = roleService.getRolesByUserId(userId);
            return Result.success("查询成功", roles);
        } catch (Exception e) {
            log.error("获取用户角色列表失败: {}", e.getMessage(), e);
            return Result.error("查询失败");
        }
    }
}

